<template>
  <el-dialog :title="title" v-model="open" :close-on-click-modal="false" width="70%" append-to-body>
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="订单号" prop="erpOrderNo">
        <el-input
          v-model="queryParams.erpOrderNo"
          placeholder="请输入订单号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="prodName">
        <el-input
          v-model="queryParams.prodName"
          placeholder="请输入产品名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="线边仓" prop="storehouseCode">
        <el-select clearable filterable v-model="queryParams.storehouseCode" style="width: 240px">
          <el-option
            v-for="(item, index) in storehouseList"
            :key="index"
            :value="item.storehouseCode"
            :label="item.storehouseName"
          >
            <span>{{ item.storehouseName }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="质检结果" prop="testingResult">
        <el-select
          v-model="queryParams.testingResult"
          placeholder="请选择质检结果"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="(item, index) in quality_testing_result"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="proTableRef"
      v-loading="loading"
      :data="tableData"
      maxHeight="500px"
      border
      show-overflow-tooltip
      @select="handleSelectionChange"
      @select-all="selectAll"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="erpOrderNo" />
      <el-table-column label="订单来源" align="center" prop="source">
        <template #default="scope">
          <dict-tag :options="order_source" :value="scope.row.source" />
        </template>
      </el-table-column>
      <el-table-column label="产品编号" align="center" prop="prodNo"></el-table-column>

      <el-table-column label="产品名称" align="center" prop="prodName" />
      <el-table-column label="批次号" align="center" prop="batchNo" />

      <el-table-column label="线边仓" align="center" prop="storehouseName" />
      <el-table-column label="库位" align="center" prop="binName" />
      
      <el-table-column label="可用库存" align="center" prop="availableNum" />
      <el-table-column label="单位" align="center" prop="packageUnit" />
      <el-table-column label="质检结果" prop="testingResult">
          <template #default="scope">
            <dict-tag
              v-if="scope.row.testingResult"
              :options="quality_testing_result"
              :value="scope.row.testingResult"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="MatDialog">
import { listStock } from "@/api/warehouse/stock";
import { listStorehouse } from "@/api/storehouse/storehouse";
import {floatSub} from "@/utils/mathCount"
import { toRefs, reactive, ref, getCurrentInstance, watch, nextTick } from "vue";

const props = defineProps(["factory", "line", "workshop", "section", "hasSelectedProList"]);
const arrInfoSelection = ref([]);
const proTableRef = ref();
const open = defineModel();
const loading = ref(true);
const showSearch = ref(true);
const tableData = ref([]);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const selectData = ref([]);
const storehouseList = ref([]);
const total = ref(0);
const title = ref("");
const queryRef = ref("queryRef");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    matType: "pc",
    equipNo: undefined,
    name: undefined,
    status: undefined,
  },
});
const { proxy } = getCurrentInstance();
const { queryParams } = toRefs(data);
const { order_source } = proxy.useDict("order_source");
const { quality_testing_result } = proxy.useDict("quality_testing_result");
const { factory, workshop, line, section, hasSelectedProList } = toRefs(props);
watch(
  () => open.value,
  (newValue) => {
    if (newValue) {
      getStorehouseList();

      arrInfoSelection.value = [];
      // 第一次进来
      if (newValue == true) {
        getList();
      }
      // 多次进来回显
      if (newValue == true && hasSelectedProList.value && hasSelectedProList.value.length > 0) {
        arrInfoSelection.value = hasSelectedProList.value;
        getList();
      }
    }
  },
  {
    immediate: true,
  }
);

const emit = defineEmits(["change"]);

function getStorehouseList() {
  listStorehouse({
    factoryCode: factory.value,
    workshopCode: workshop.value,
    lineCode: line.value,
    sectionCode: section.value,
    pageNum: 1,
    pageSize: 1000,
  }).then((res) => {
    storehouseList.value = res.rows;
  });
}

/** 查询字典类型列表 */
function getList() {
  loading.value = true;
  const params = {
    factoryCode: factory.value,
    workshopCode: workshop.value,
    lineCode: line.value,
    sectionCode: section.value,
    ...queryParams.value,
  };
  listStock(params)
    .then((response) => {
      tableData.value = response.rows;
      total.value = response.total;
      loading.value = false;
      if(tableData.value.length ){
        tableData.value.forEach((item) => {
          item.availableNum = floatSub(item.num,item.frozenNum)
        });
      }
      nextTick(() => {
        if (tableData.value.length && arrInfoSelection.value.length) {
          tableData.value.forEach((item) => {
            const include = arrInfoSelection.value.filter((info) => info.id == item.id);
            if (include.length) {
              proTableRef.value.toggleRowSelection(item, true);
            } else {
              proTableRef.value.toggleRowSelection(item, false);
            }
            
          });
        }
      });
    })
    .catch(() => {
      loading.value = true;
    });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection, row) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  // selectData.value = selection;
  let selected = selection.length && selection.indexOf(row) !== -1;
  if (selected) {
    arrInfoSelection.value.push(row);
  } else {
    arrInfoSelection.value = arrInfoSelection.value.filter((item) => item.id != row.id);
  }
}
// 全选 或全不选
function selectAll(section) {
  if (section.length) {
    // 全选  push
    section.forEach((item) => {
      arrInfoSelection.value.push(item);
    });
  } else {
    // 全不选  当页数据  删除
    if (tableData.value.length && arrInfoSelection.value.length) {
      tableData.value.forEach((item) => {
        arrInfoSelection.value = arrInfoSelection.value.filter((info) => item.id != info.id);
      });
    }
  }
  arrInfoSelection.value = uniqueObjects(arrInfoSelection.value);
}

// 数组对象去重
function uniqueObjects(arr) {
  const seen = new Map();
  return arr.filter((item) => {
    // 将对象转换为字符串（或其他可以唯一表示对象的内容）
    const key = JSON.stringify(item);
    // 如果 Map 中还没有这个键，则添加它并返回 true
    if (!seen.has(key)) {
      seen.set(key, item);
      return true;
    }
    // 如果已经有了，就返回 false，表示这个对象应该被过滤掉
    return false;
  });
}
function submitForm() {
  console.log("selected", selectData.value);
  if (arrInfoSelection.value?.length && arrInfoSelection.value.length > 0) {
    open.value = false;
    emit("change", JSON.parse(JSON.stringify(arrInfoSelection.value)));
  } else {
    proxy.$modal.msgError("请选择至少一条产品！");
  }
}
</script>

<style lang="scss" scoped></style>
